﻿
namespace CmdArgs.Validation.Options
{
    using CmdArgs.Settings;

    /// <summary>
    /// Validates whether the parameters' values are integers.
    /// Optionally it may also validates whether the values are in specific range.
    /// </summary>
    public sealed class IntOptionValidator : ValueValidatorTemplate
    {
        private int min = int.MinValue;
        private int max = int.MaxValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="IntOptionValidator"/> class.
        /// </summary>
        /// <param name="min">The inclusive minimal value.</param>
        /// <param name="max">The exclusive maximal value.</param>
        public IntOptionValidator(int min, int max)
        {
            this.max = max;
            this.min = min;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="IntOptionValidator"/> class
        /// without minimal and maximal value.
        /// </summary>
        public IntOptionValidator() 
        { 
        }

        protected override ValidationResult Validate(string value, OptionSettings option)
        {
            int result;
            if (int.TryParse(value, out result))
            {
                if (this.min > result || result >= this.max)
                {
                    string message = string.Format("Value {0} is not between {1} and {2}", value, this.min, this.max);
                    return new ValidationResult(new ValidationError(message, option));
                }

                return ValidationResult.GetValidResult();
            }
            else
            {
                string message = string.Format("Value {0} is not integer.", value);
                return new ValidationResult(new ValidationError(message, option));
            }
        }
    }
}
